/*******************************************************************************
 * KindEditor - 图片批量上传插件
 * Copyright (C) 2018-2022 reui.cn
 *
 * @author Jayter <135566499@qq.com>
 * @site http://www.reui.cn/
 *******************************************************************************/
(function (K) {

    function multiUpload(options, lang) {
        this.init(options, lang);
    }
    K.extend(multiUpload, {
        init: function (options, lang) {
            var self = this;
            options.afterError = options.afterError || function (str) {
                alert(str);
            }; console.log(options)
            self.options = options;
            self.lang = lang;
            self.progressbars = {};
            self.div = K(options.container).html([
                '<div class="ke-swfupload">',
                '<div class="ke-swfupload-top">',
                '<div class="ke-inline-block ke-swfupload-button">',
                '<div id="multi-picker" type="button">' + options.label + '(Browse)</div>',
                '</div>',
                '<div class="ke-inline-block ke-swfupload-desc">' + options.uploadDesc + '</div>',
                '<span class="ke-button-common ke-button-outer ke-swfupload-startupload">',
                '<input type="button" id="multi-startup" class="ke-button-common ke-button" value="' + lang.startUpload + '" />',
                '</span>',
                '</div>',
                '<div class="ke-swfupload-body"></div>',
                '</div>'
            ].join(''));
            self.bodyDiv = K('.ke-swfupload-body', self.div);

            function showError(itemDiv, msg) {
                K('.ke-status > div', itemDiv).hide();
                K('.ke-message', itemDiv).addClass('ke-error').show().html(K.escape(msg));
            }
            self.uploaders = WebUploader.create({
                server: options.server,
                pick: '#multi-picker',
                threads: 1,
                fileSingleSizeLimit: self.options.maxSize * 1024 * 1024, //5M
                fileNumLimit: self.options.numLimit,
                fileVal: self.options.postName || 'image',
                auto: false,
                compress: {
                    quality: 89,
                    width: options.maxWidth || 900,
                    height: options.maxHeight || 1200,
                    compressSize: 64 * 1024, //如小于此值不会压缩(字节)
                    noCompressIfLarger: false, //如压后比原大则用原图(可能影响自纠正)
                },
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,png',
                    mimeTypes: 'image/*'
                },
                thumb: {
                    quality: 90,
                    type: 'image/jpeg'
                }
            });
            if (options.ifloaded) {
                K('.webuploader-pick', self.div).css('padding', '3px');
            } else {
                K('.webuploader-pick', self.div).css('text-indent', '-1000%');
            }
            // 当有文件添加进来的时候
            self.uploaders.on('fileQueued', function (file) {
                if (file.type.split('/')[0] == 'image') {
                    self.uploaders.makeThumb(file, function (error, imgsrc) {
                        if (!error) self.appendFile(file, imgsrc);
                    }, 80, 80);
                }
            });
            self.uploaders.on('uploadStart', function (file) {
                var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv);
                K('.ke-status > div', itemDiv).hide();
                K('.ke-progressbar', itemDiv).show();
            });
            self.uploaders.on('uploadProgress', function (file, percent) {
                var progressbar = self.progressbars[file.id];
                percent = percent * 100;
                progressbar.bar.css('width', Math.round(percent * 80 / 100) + 'px');
                progressbar.percent.html(percent + '%');
            });
            self.uploaders.on('uploadError', function (file) {
                console.log('uploadError', file);
                var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
                showError(itemDiv, lang.uploadError);
            });
            self.uploaders.on('uploadSuccess', function (file, res) {
                var itemDiv = K('div[data-id="' + file.id + '"]', self.bodyDiv).eq(0);
                if (res.code != 1) {
                    showError(itemDiv, K.DEBUG ? res.msg : lang.uploadError);
                    return;
                }
                K('.ke-img', itemDiv).attr('data-status', 1).data('data', res.data);
                K('.ke-progressbar', itemDiv).hide(); //.ke-status > div
                K('.ke-message', itemDiv).addClass('ke-success').show().html(K.lang('uploadSuccess'));
            });
            self.uploaders.on('uploadComplete', function (file) { });
            self.uploaders.on("error", function (type) {
                if (type == "Q_TYPE_DENIED") {
                    alert(lang.invalidFiletype);
                } else if (type == "F_EXCEED_SIZE") {
                    alert(options.uploadDesc);
                } else if (type == 'F_DUPLICATE') {
                    //layer.msg('有文件重复选择,未加入上传框！');
                } else if (type == 'Q_EXCEED_NUM_LIMIT') {
                    alert(options.uploadDesc);
                } else {
                    alert(lang.unknownError + ':' + type);
                }
            });
            K('#multi-startup', self.div).click(function () {
                self.uploaders.upload();
            });
        },
        urlList: function () {
            var list = [];
            K('.ke-img', self.bodyDiv).each(function () {
                var img = K(this);
                if (img.attr('data-status') == 1) {
                    list.push(img.data('data'));
                }
            });
            return list;
        },
        removeFile: function (fileId) {
            var self = this;
            self.uploaders.removeFile(self.uploaders.getFile(fileId));
            var itemDiv = K('div[data-id="' + fileId + '"]', self.bodyDiv);
            K('.ke-photo', itemDiv).unbind();
            K('.ke-delete', itemDiv).unbind();
            itemDiv.remove();
        },
        removeFiles: function () {
            var self = this;
            K('.ke-item', self.bodyDiv).each(function () {
                self.removeFile(K(this).attr('data-id'));
            });
        },
        appendFile: function (file, imgsrc) {
            var self = this;
            var itemDiv = K('<div class="ke-inline-block ke-item" data-id="' + file.id + '"></div>');
            self.bodyDiv.append(itemDiv);
            var photoDiv = K('<div class="ke-inline-block ke-photo"></div>').mouseover(function (e) {
                K(this).addClass('ke-on');
            }).mouseout(function (e) {
                K(this).removeClass('ke-on');
            });
            itemDiv.append(photoDiv);
            var img = K('<img src="' + imgsrc + '" class="ke-img" data-status="0" width="80" height="80" alt="' + file.name + '" />');
            photoDiv.append(img);
            K('<span class="ke-delete"></span>').appendTo(photoDiv).click(function () {
                self.removeFile(file.id);
            });
            var statusDiv = K('<div class="ke-status"></div>').appendTo(photoDiv);
            // progressbar
            K(['<div class="ke-progressbar">',
                '<div class="ke-progressbar-bar"><div class="ke-progressbar-bar-inner"></div></div>',
                '<div class="ke-progressbar-percent">0%</div></div>'
            ].join('')).hide().appendTo(statusDiv);
            // message
            K('<div class="ke-message">' + self.lang.pending + '</div>').appendTo(statusDiv);

            itemDiv.append('<div class="ke-name">' + file.name + '</div>');

            self.progressbars[file.id] = {
                bar: K('.ke-progressbar-bar-inner', photoDiv),
                percent: K('.ke-progressbar-percent', photoDiv)
            };
        },
        remove: function () {
            this.removeFiles();
            this.div.html('');
        }

    });

    K.multiUpload = function (element, options) {
        return new multiUpload(element, options);
    };

})(KindEditor);




//====================================
KindEditor.plugin('multiimage', function (K) {
    var self = this,
        name = 'multiimage',
        uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php'),
        imgPath = self.pluginsPath + 'multiimage/images/',
        allowImageSize = K.undef(self.allowImageSize, 5), //5M
        //imageFileTypes = K.undef(self.imageFileTypes, '*.jpg;*.gif;*.png'),
        imageFileLimit = K.undef(self.imageFileLimit, 10),
        filePostName = K.undef(self.filePostName, 'image'),
        lang = self.lang(name + '.');

    self.plugin.loadJs = function (url, callback) {
        if (document.getElementById('multiimage')) {
            callback && callback();
            return;
        }
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.id = 'multiimage';
        script.onload = function () {
            callback && callback();
        }
        script.src = url;
        document.body.append(script);
    }
    self.plugin.multiImageDialog = function (options) {
        var clickFn = options.clickFn;
        var uploadDesc = K.tmpl(lang.uploadDesc, { uploadLimit: imageFileLimit, sizeLimit: allowImageSize + 'M' });
        var html = [
            '<div style="padding:20px 10px;">',
            '<div class="swfupload">',
            '</div>',
            '</div>'
        ].join('');
        var multiUpload, dialog = self.createDialog({
            name: name,
            width: 650,
            height: 510,
            title: self.lang(name),
            body: html,
            previewBtn: {
                name: lang.insertAll,
                click: function (e) {
                    clickFn.call(self, multiUpload.urlList());
                    //console.log('previewBtn.click', e)
                }
            },
            yesBtn: {
                name: lang.clearAll,
                click: function (e) {
                    multiUpload.removeFiles();
                    console.log('yesBtn', e)
                }
            },
            beforeRemove: function () {
                // IE9 bugfix: https://github.com/kindsoft/kindeditor/issues/72
                if (!K.IE || K.V <= 8) {
                    multiUpload.remove();
                    console.log('beforeRemove');
                }
            }
        });
        var div = dialog.div;
        var ifloaded = typeof (WebUploader) == 'object';
        var loadHandler = function () {
            multiUpload = K.multiUpload({
                container: K('.swfupload', div),
                server: uploadJson,
                maxSize: allowImageSize,
                numLimit: imageFileLimit,
                postName: filePostName,
                uploadDesc: uploadDesc,
                maxWidth: K.undef(self.maxWidth, 900),
                maxHeight: K.undef(self.maxHeight, 1200),
                ifloaded: ifloaded,
                label: self.lang('image.upload')
            }, lang);
        }
        if (ifloaded) {
            loadHandler()
        } else {
            self.plugin.loadJs(self.pluginsPath + 'multiimage/uploader.min.js', function () {
                loadHandler()
            });
        }
        return dialog;
    }




    self.clickToolbar(name, function () {
        self.plugin.multiImageDialog({
            clickFn: function (urlList) {
                if (urlList.length == 0) {
                    return;
                }
                K.each(urlList, function (i, data) {
                    if (self.afterUpload) {
                        self.afterUpload.call(self, data.url, data, 'multiimage');
                    }
                    self.exec('insertimage', data.url, data.title, data.width, data.height, data.border, data.align);
                });
                // Bugfix: [Firefox] 上传图片后，总是出现正在加载的样式，需要延迟执行hideDialog
                setTimeout(function () {
                    self.hideDialog().focus();
                }, 0);
            }
        });
    });
});